import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CodeEntity } from 'src/common/entities/code.entity';
import * as svgCaptcha from 'svg-captcha';
import { Repository } from 'typeorm';

@Injectable()
export class VerificationCodeService {
  @InjectRepository(CodeEntity)
  private readonly codeRepository: Repository<CodeEntity>;

  async captche(size = 4) {
    const captcha = svgCaptcha.create({
      //可配置返回的图片信息
      size, //生成几个验证码
      fontSize: 50, //文字大小
      width: 100, //宽度
      height: 34, //高度
      background: '#cc9966', //背景颜色
    });
    return captcha;
  }

  async saveCode(ma: string) {
    const code = new CodeEntity();
    code.code = ma;
    this.codeRepository.save(code);
    return '保存成功';
  }

  async findAll() {
    return this.codeRepository
      .createQueryBuilder('CodeEntity')
      .orderBy('CodeEntity.created_at', 'DESC')
      .getMany();
  }

  async removeAllCode() {
    return this.codeRepository
      .createQueryBuilder('CodeEntity')
      .delete()
      .execute();
  }
}
